package com.atguigu.guli.service.cms.controller.api;


import com.atguigu.guli.service.base.result.R;
import com.atguigu.guli.service.cms.service.AdService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 广告推荐 前端控制器
 * </p>
 *
 * @author atguigu
 * @since 2021-08-08
 */
@RestController

@RequestMapping("/api/cms/ad")
public class ApiAdController {
    @Autowired
    AdService adService;

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @GetMapping("set")
    public R setK(){
        redisTemplate.opsForValue().set("k1","v1");//会将数据序列化之后存入redis
        redisTemplate.opsForValue().set("k3","v3",100, TimeUnit.SECONDS);//设置过期时间
        redisTemplate.opsForValue().set("k4",new Date());
        redisTemplate.opsForValue().set("k5",R.ok());
        stringRedisTemplate.opsForValue().set("k2","v2");//只能保存字符串
        stringRedisTemplate.opsForValue().set("k6",new Gson().toJson(new Date()));
        stringRedisTemplate.opsForValue().set("k7",new Gson().toJson(R.ok())); //报错  R类是自定义类，没有实现序列化  要手动加implements Serializable 实现下
        return R.ok();                                                              //或手动抽取配置一个自动序列化器配置
    }

    @GetMapping("get")
    public R getK(){
        Object k1 = redisTemplate.opsForValue().get("k1");
        Object k4 = redisTemplate.opsForValue().get("k4");
        System.out.println("k4 = " + k4);
        Object k5 = redisTemplate.opsForValue().get("k5");
        System.out.println("k5 = " + k5.getClass().getName());
        System.out.println("k1 = " + k1);
        Boolean hasKey = stringRedisTemplate.hasKey("k2");//判段k2是否有值，有就打印
        Date k6 = new Gson().fromJson(stringRedisTemplate.opsForValue().get("k6"), Date.class);
        System.out.println("k6 = " + k6);
        R k7 = new Gson().fromJson(stringRedisTemplate.opsForValue().get("k7"), R.class);
        System.out.println("k7 = " + k7);
        if (hasKey){
            String k2 = stringRedisTemplate.opsForValue().get("k2");
            System.out.println("k2 = " + k2);
        }

        return R.ok();
    }

    //查询首页热门数据的方法
    //前端查询所有的热门数据  然后在业务代码中根据类型分为  三个广告类型的数据集合

    @GetMapping("list")
    public R listAds(){
        Map<String , Object> adsMap =adService.getAds();//查询所有的热门数据  并分成不同的数据集合

        return R.ok().data(adsMap);
    }
}

